<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="JUST DO IT.">
<meta property="og:type" content="website">
<meta property="og:title" content="Srtian&#39;Blog">
<meta property="og:url" content="http://srtian96.gitee.io/blog/page/2/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="JUST DO IT.">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Srtian&#39;Blog">
<meta name="twitter:description" content="JUST DO IT.">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/page/2/"/>





  <title>Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left 
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/10/09/JavaScript函数式编程（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/10/09/JavaScript函数式编程（一）/" itemprop="url">JavaScript函数式编程（一）</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-09T12:40:59+08:00">
                2018-10-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,149
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>国庆期间回到了学校，生活也开始规律起来。但国庆期间也没有怎么学习，只是零散的在掘金上看了几篇文章，也算是给自己放了一个小长假。但假期已经结束，生活还得继续，学习也是。发现这几个月自己所学习的东西很多都和函数式编程有关，但一直没好好的对其进行一个总结，因此打算对JavaScript函数式编程进行一个总结。这篇主要是对函数式编程的一些思想做一个讨论，后面一篇则是对JavaScript函数式编程的具体使用做一些讨论（后面一篇文章要等看完youtube上的视频后再写啦~）</p>
<h3 id="一。函数式编程概述"><a href="#一。函数式编程概述" class="headerlink" title="一。函数式编程概述"></a>一。函数式编程概述</h3><p>首先我们需要函数式编程，主要是因为函数式编程的可读性和可维护性都较好，下图是《JavaScript轻量级函数式编程》所提供的一张图：</p>
<p><img src="https://upload-images.jianshu.io/upload_images/1217488-dc896f336c5d0095.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/611" alt="image"></p>
<p>我们可以看到，如果我们在恰当的时候使用函数式编程可以有效的提高我们代码的可读性。另外函数式编程可以有效的提高我们代码的可维护性，这在后面也会有所讨论。</p>
<p>要了解函数式编程，首先就应当了解什么是函数，学过数学的应该对这个等式很熟悉：y = f(x)。我们可以看到，在数学中，一个函数总是接受输入，并且总是给出输出。而在FP中也是如此，在FP中有个术语叫做“态射（morphism）”，这个词用来描述一个值的集合映射到另一值的集合，就像一个函数的输入与这个函数的输出的关系一样。</p>
<p>而函数与过程区别就在于：如果我们考虑过程，那么一个任意功能的集合，它可能有输入，也可能没有，它可能有输出也可能没有；而一个函数接受数据输入并总是有一个return。当我们打算进行函数式编程的时候，我们就尽可能多的使用函数，而不是过程。</p>
<p>但这里的，我们使用函数式编程也是要对函数的使用是有一些要求，这也是函数式编程思想的体现，总的来说有以下几点：</p>
<ul>
<li>声明式</li>
<li>纯函数</li>
<li>数据的不可变</li>
</ul>
<h3 id="二、声明式"><a href="#二、声明式" class="headerlink" title="二、声明式"></a>二、声明式</h3><p>既然有了声明式，那么与之相对的就是命令式的了。其实命令式的编程在我们的日常编程中是最常见的一种编程方式了。举个很简单的例子，如果我们要实现一个数组的元素全部加一，通常来说我们会这样做：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]</span><br><span class="line"><span class="keyword">const</span> addOne = <span class="function">(<span class="params">arr</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> result = []</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">        result.push(arr[i] + <span class="number">1</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br><span class="line">addOne(arr)</span><br></pre></td></tr></table></figure>
<p>这样做乍看起来好像还可以，即实现了我们既定的目标，代码逻辑上比较清晰。但仔细想一想，在这里我们想要的是所有数组的元素都加一，那如果我们再此基础上想再实现一个所有元素加十呢，那么是不是还需要在这样做一次：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]</span><br><span class="line"><span class="keyword">const</span> addTen = <span class="function">(<span class="params">arr</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> result = []</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">        result.push(arr[i] + <span class="number">10</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br><span class="line">addOne(arr)</span><br></pre></td></tr></table></figure>
<p>可以清楚的看到，我们两次的代码几乎一模一样，唯一不同的就是这一句语句：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">result.push(arr[i] + <span class="number">1</span>)</span><br><span class="line">result.push(arr[i] + <span class="number">10</span>)</span><br></pre></td></tr></table></figure>
<p>因此我们就可以再此基础上这段代码进行抽象，来实现简化代码的目的,下面是一个简单的实现：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]</span><br><span class="line"><span class="keyword">const</span> getNew = <span class="function">(<span class="params">arr, fun</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> result = []</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">            result.push(fun(arr[i]))</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> addOne = <span class="function"><span class="params">item</span> =&gt;</span> item + <span class="number">1</span></span><br><span class="line"><span class="keyword">const</span> addTen = <span class="function"><span class="params">item</span> =&gt;</span> item + <span class="number">10</span></span><br><span class="line"><span class="keyword">const</span> getOne = getNew(arr, addOne)</span><br><span class="line"><span class="keyword">const</span> getTen = getNew(arr, addTen)</span><br></pre></td></tr></table></figure>
<p>我们可以看到，这样做我们在往后如果还需实现诸如加二十，乘二之类的操作时，就无需再将循环的逻辑再实现一遍了，只需将其所要完成的任务传入即可，当然这对数组我以上的方法还是麻烦了一些，我只是为了举个例子而已，JavaScript的数组直接为我们提供了map方法可以让我们非常容易的就实现了上述功能：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> addOne = <span class="function"><span class="params">arr</span> =&gt;</span> arr.map(<span class="function"><span class="params">item</span> =&gt;</span> item + <span class="number">1</span>)</span><br><span class="line"><span class="keyword">const</span> addTen = <span class="function"><span class="params">arr</span> =&gt;</span> arr.map(<span class="function"><span class="params">item</span> =&gt;</span> item + <span class="number">10</span>)</span><br></pre></td></tr></table></figure>
<p>是不是代码非常简单明了，以上的两种方法都将for循环给封装起来了，我们只需去完成我们想要完成的功能的代码的编写即可，无需去关心其他的一些内部的实现。但如果这样的话，我们就需要考虑的是，在这些被忽略的实现里，是否会产生一些副作用的操作了，也正是由于这个原因，函数式编程又有了以下两个要求：纯函数and数据不可变</p>
<h3 id="三、纯函数"><a href="#三、纯函数" class="headerlink" title="三、纯函数"></a>三、纯函数</h3><p>熟悉redux的朋友应该都知道，redux 里的 reducer 就是一个纯函数，根据传入的 action creates 来更改 store 树。而所谓的纯函数，主要指的就是满足了一下两个条件的函数：</p>
<ul>
<li>函数不会对外部的状态造成影响。</li>
<li>函数的执行过程完全有输入的参数所决定，不会受参数之外的任何数据的影响。</li>
</ul>
<p>对于这两方面可以看一个示例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line"><span class="keyword">const</span> addVal = <span class="function">(<span class="params">arr, newVal</span>) =&gt;</span> &#123;</span><br><span class="line">    arr.push(newVal)</span><br><span class="line">    <span class="keyword">return</span> arr</span><br><span class="line">&#125;</span><br><span class="line">addVal(arr, <span class="number">6</span>)</span><br><span class="line"><span class="built_in">console</span>.log(arr) <span class="comment">// [1, 2, 3, 4, 6]</span></span><br></pre></td></tr></table></figure>
<p>就比如上面的代码，add函数会直接调用push函数，将新元素直接添加到数组的尾部，这样就会直接更改数组的值。这样看起来好像并没有什么副作用，但仔细想想，加入这是一份数据，当我们将数据传入这个函数的时候，会将原数据进行直接修改，这很容易导致其他引用此数据的函数出现意料不到的问题，就比如下面这个：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line"><span class="keyword">const</span> addOne = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.map(<span class="function"><span class="params">newVal</span> =&gt;</span> newVal + <span class="number">1</span>)</span><br><span class="line"><span class="keyword">const</span> addVal = <span class="function">(<span class="params">arr, newVal</span>) =&gt;</span> &#123;</span><br><span class="line">    arr.push(newVal)</span><br><span class="line">    <span class="keyword">return</span> arr</span><br><span class="line">&#125;</span><br><span class="line">addVal(arr, <span class="number">6</span>)</span><br><span class="line">addOne(arr)</span><br></pre></td></tr></table></figure>
<p>可以看到上述代码，我们在addOne(arr)所期望的结果是arr数组内的所有元素都加上1，但实际结果却是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[2, 3, 4, 5, 7]</span><br></pre></td></tr></table></figure>
<p>所产生的结果与我们所预料的完全不同。也正是出于这番原因，我们在使用redux的时候，在reducer中，也要求reducer是一个纯函数。就是为了避免诸如此类的事情的发生。出于这番考虑，我们就可以通过对上述代码进行修改，以满足我们的需求：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]</span><br><span class="line"><span class="keyword">const</span> addOne = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.map(<span class="function"><span class="params">newVal</span> =&gt;</span> newVal + <span class="number">1</span>)</span><br><span class="line"><span class="keyword">const</span> addVal = <span class="function">(<span class="params">arr, newVal</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> [...arr, newVal]</span><br><span class="line">&#125;</span><br><span class="line">addVal(arr, <span class="number">6</span>)</span><br><span class="line">addOne(arr)</span><br></pre></td></tr></table></figure>
<p>现在再去执行，就可以发现，我们所得的结果与我们所期望的是一致的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[2, 3, 4, 5]</span><br><span class="line">[1, 2, 3, 4, 6]</span><br></pre></td></tr></table></figure>
<p>上面所说的副作用很简单，除此之外还有很多“不纯”的操作：</p>
<ul>
<li>读取用户的输入</li>
<li>改变全局变量的值</li>
<li>改变输入参数引用的对象，就像我们上面所演示的</li>
<li>操作DOM元素</li>
<li>网络输入或输出</li>
<li>等等</li>
</ul>
<h3 id="四、数据不可变"><a href="#四、数据不可变" class="headerlink" title="四、数据不可变"></a>四、数据不可变</h3><p>数据不可变与纯函数其实也是紧密相关的，上面所提到的纯函数，其实也是数据不可变的一种体现。而所谓的数据的不可变就是通过产生新的数据来体现变化，从而保持原有的数据不变。这种思想再redux中的reducer中也得到了体现，我们对所传入的数据不是直接进行更改，而是使用诸如object.assign()、扩展符、元数组等方法产生一个新的状态，从而来对store树进行改变。此外Immutable也很出名~</p>
<p>（数据的不可变在TypeScript中也得到了很好的支持（至少是在类型方面），此外ES6所提供的const也是支持变量的常量化，所以我认为数据不可变应该在往后也会是越发推广的一种思想吧。）</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/09/24/浅谈Web路由/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/09/24/浅谈Web路由/" itemprop="url">浅谈Web路由</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-24T11:46:50+08:00">
                2018-09-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/浏览器/" itemprop="url" rel="index">
                    <span itemprop="name">浏览器</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,982
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="关于秋招的一些感想"><a href="#关于秋招的一些感想" class="headerlink" title="关于秋招的一些感想"></a>关于秋招的一些感想</h3><p>最近一段时间忙着秋招，一路经历了阿里终面挂，美团终面挂等等，感觉自己有点苦逼（尤其是因为没HC而挂是最难受的）。虽然到现在还没得到满意的结果，但这个过程还是有所收获的，这是虽然一个自我怀疑的过程，但也是一个不断弥补自身不足，学习的过程，其中与一些面试我的师兄在交流的过程中也是受益匪浅，并且也对自身以后要走的路有了一个更加明确的认识，所以前途漫漫还需努力呀！</p>
<h3 id="一、路由"><a href="#一、路由" class="headerlink" title="一、路由"></a>一、路由</h3><p>在现代前端开发中，路由是非常重要的一环。但路由到底是什么呢？有些说：路由就是指随着浏览器地址栏的变化，展示给用户的页面也不相同。这是从路由的用途上来解释路由是什么的，还有一种说法是：路由就是URL到函数的映射。这是从路由的实现原理上来解释路由是什么的。这两种说法都很有道理，但我个人认为还是第二种比较切合我自己对路由的理解吧。</p>
<p>上面已经说了上面是路由，而路由本身也经历了不同的发展阶段：</p>
<ol>
<li>后端路由</li>
<li>前端路由</li>
</ol>
<p>后端路由又可称之为服务器端路由，因为对于服务器来说，当接收到客户端发来的HTTP请求，就会根据所请求的相应URL，来找到相应的映射函数，然后执行该函数，并将函数的返回值发送给客户端。对于最简单的静态资源服务器，可以认为，所有URL的映射函数就是一个文件读取操作。对于动态资源，映射函数可能是一个数据库读取操作，也可能是进行一些数据的处理，等等。然后根据这些读取的数据，在服务器端就使用相应的模板来对页面进行渲染后，再返回渲染完毕的页面。这种方式在早期的前端开发中非常普遍，它的好处与坏处都很明显：</p>
<ul>
<li>好处：安全性好，SEO好。</li>
<li>缺点：加大服务器的压力，不利于用户体验，代码冗合。</li>
</ul>
<p>也正是由于后端路由还存在着自己的不足，前端路由才有了属于自己的一片天地与发展的空间。对于前端路由来说，路由的映射函数通常是进行一些DOM的显示和隐藏操作。这样，当访问不同的路径的时候，会显示不同的页面组件。前端路由主要有以下两种实现方案：</p>
<ul>
<li>hash</li>
<li>history API</li>
</ul>
<p>当然，前端路由也存在缺陷：使用浏览器的前进，后退键时会重新发送请求，来获取数据，没有合理地利用缓存。但总的来说，现在前端路由已经是实现路由的主要方式了，我们常用的诸如react-router等前端框架的路由控制都是基于前端路由进行开发的，因此将前端路由进行一个了解<br>还是很有必要的。</p>
<h3 id="二、前端路由的实现"><a href="#二、前端路由的实现" class="headerlink" title="二、前端路由的实现"></a>二、前端路由的实现</h3><h4 id="2-1-基于hash"><a href="#2-1-基于hash" class="headerlink" title="2.1 基于hash"></a>2.1 基于hash</h4><p>早期的前端路由的实现就是基于location.hash来实现的。其实现原理也很简单，location.hash的值就是URL中#后面的内容。比如下面这个网站，它的location.hash=’#me’：</p>
<blockquote>
<p><a href="https://www.srtian.com#me" target="_blank" rel="noopener">https://www.srtian.com#me</a></p>
</blockquote>
<p>此外，hash也存在下面几个特性：</p>
<ul>
<li>URL中hash值只是客户端的一种状态，也就是说当向服务器端发出请求时，hash部分不会被发送。</li>
<li>hash值的改变，都会在浏览器的访问历史中增加一个记录。因此我们能通过浏览器的回退、前进按钮控制hash的切换。</li>
<li>我们可以使用hashchange事件来监听hash的变化。</li>
</ul>
<p>出发hsah变化的方式也有两种，一种是通过a标签，并设置href属性，当用户点击这个标签后，URL就会发生改变，也就会触发hashchange事件了：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"#srtian"</span>&gt;</span>srtian<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>还有一种方式就是直接使用JavaScript来对loaction.hash进行赋值，从而改变URL，触发hashchange事件：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">location.hash=<span class="string">"#srtian"</span></span><br></pre></td></tr></table></figure>
<h4 id="2-2-基于History-API"><a href="#2-2-基于History-API" class="headerlink" title="2.2 基于History API"></a>2.2 基于History API</h4><p>前面的hash虽然也很不错，但使用时都需要加上#，并不是很美观。因此到了HTML5，又提供了History API来实现URL的变化。其中做最主要的API有以下两个：history.pushState()和history.repalceState()。</p>
<p>这两个API可以在不进行刷新的情况下，操作浏览器的历史纪录。唯一不同的是，前者是新增一个历史记录，后者是直接替换当前的历史记录。此外，这两个api都接受三个参数：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.history.pushState(<span class="literal">null</span>, <span class="literal">null</span>, <span class="string">"http://www.163.com"</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li>状态对象（state object）：一个JavaScript对象，与用pushState()方法创建的新历史记录条目关联。无论何时用户导航到新创建的状态，会触发popstate事件，并能在事件中使用该对象。</li>
<li>标题（title）：一般浏览器会忽略，最好传入null。</li>
<li>地址（URL）：就是需要新增的历史记录的地址，浏览器不会去直接加载改地址，但后面也可能会去尝试加载该地址。此外需要注意的是，传入的URL与当前URL应该是同源的。</li>
</ul>
<p>这一块的详情可以去看MDN，它做了一个比较详细的介绍：</p>
<blockquote>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/History" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/API/History</a></p>
</blockquote>
<p>此外，还提供了popstate事件来监听历史记录的变化。</p>
<p>可以看看下面这个实例：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span> <span class="attr">id</span>=<span class="string">"example"</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/name"</span> <span class="attr">title</span>=<span class="string">"name"</span>&gt;</span>name<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/age"</span> <span class="attr">title</span>=<span class="string">"age"</span>&gt;</span>age<span class="tag">&lt;/<span class="name">a</span>&gt;</span>?</span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"main"</span> <span class="attr">id</span>=<span class="string">"main"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">;(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> examplebox = <span class="built_in">document</span>.getElementById(<span class="string">'example'</span>)</span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> mainbox = <span class="built_in">document</span>.getElementById(<span class="string">'main'</span>)</span></span><br><span class="line"><span class="undefined">    </span></span><br><span class="line"><span class="javascript">    examplebox.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;</span></span><br><span class="line"><span class="undefined">        e.preventDefault()</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> elm = e.target</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> uri = elm.href</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> tlt = elm.title</span></span><br><span class="line"><span class="javascript">        history.pushState(&#123;<span class="attr">path</span>:uri,<span class="attr">title</span>:tlt&#125;, <span class="literal">null</span>, uri)</span></span><br><span class="line"><span class="javascript">        mainbox.innerHTML = <span class="string">'current page is '</span>+tlt</span></span><br><span class="line"><span class="undefined">    &#125;)</span></span><br><span class="line"><span class="javascript">    <span class="built_in">window</span>.addEventListener(<span class="string">'popstate'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> state = e.state</span></span><br><span class="line"><span class="javascript">        mainbox.innerHTML = <span class="string">'current page is '</span> + state.title</span></span><br><span class="line"><span class="undefined">    &#125;)</span></span><br><span class="line"><span class="undefined">&#125;)()</span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>两种实现方式的对比：基于Hash的路由实现，兼容性更好；而基于History API的路由，则更正式，更美观，可以设置与当前URL同源的任意URL，路径更直观。此外，基于Hash的路由不需要对服务器做改动，基于History API的路由需要对服务器做一些改造，需要对不同的路由进行相应的设置才行。</p>
</blockquote>
<h3 id="三、React-Router"><a href="#三、React-Router" class="headerlink" title="三、React-Router"></a>三、React-Router</h3><p>由于我现在也就对React-Router比较熟悉，Vue学了太久了，忘记了。Angular刚学，还没到路由这块这来，因此就以React-Router为例，来聊聊现代前端框架的路由实现思路。先来看看一个简单的React中的Router代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;Router&gt;</span><br><span class="line">    &lt;Switch&gt;</span><br><span class="line">        &lt;Route path=<span class="string">"/about"</span> component=&#123;About&#125;/&gt; </span><br><span class="line">        &lt;Route path=<span class="string">"/:user"</span> component=&#123;User&#125;/&gt; </span><br><span class="line">    &lt;<span class="regexp">/Switch&gt; </span></span><br><span class="line"><span class="regexp">&lt;/</span>Router&gt;</span><br></pre></td></tr></table></figure>
<p>其实现思路也很简单如下图所示：<br><img src="https://user-images.githubusercontent.com/8401872/29739490-c1dbb054-8a71-11e7-9c9f-31cbbd6adbcb.png" alt="image"></p>
<p>其实现思路很简单：About和User这两个component一直都存在。当路由发生改变时，与URL相匹配的component机会被成功渲染。而不匹配的component就设置为null。</p>
<p>具体实现，大家可以看这篇文章，这位大佬做了很详细的介绍：</p>
<blockquote>
<p><a href="https://github.com/youngwind/blog/issues/109" target="_blank" rel="noopener">https://github.com/youngwind/blog/issues/109</a></p>
</blockquote>
<p>需要注意的是，react-router的每一个路由都是一个react组件，因此在进行路由跳转时，它也会比对前后页面的差异，然后再进行渲染，因此使用react-router较之传统的路由在页面渲染上的表现也会较好。</p>
<p>参考资料：</p>
<ul>
<li><a href="https://github.com/youngwind/blog/issues/109" target="_blank" rel="noopener">https://github.com/youngwind/blog/issues/109</a></li>
<li><a href="https://zhuanlan.zhihu.com/p/24814675" target="_blank" rel="noopener">https://zhuanlan.zhihu.com/p/24814675</a></li>
<li><a href="https://segmentfault.com/a/1190000007238999" target="_blank" rel="noopener">https://segmentfault.com/a/1190000007238999</a></li>
<li><a href="http://www.cnblogs.com/yuqing6/p/6731980.html" target="_blank" rel="noopener">http://www.cnblogs.com/yuqing6/p/6731980.html</a></li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/09/19/Angular学习笔记——模板/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/09/19/Angular学习笔记——模板/" itemprop="url">Angular学习笔记——模板</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-19T16:24:08+08:00">
                2018-09-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Angular/" itemprop="url" rel="index">
                    <span itemprop="name">Angular</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  997
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  4
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="模板的使用"><a href="#模板的使用" class="headerlink" title="模板的使用"></a>模板的使用</h3><p>话说现在前端的三大框架都是使用模板来进行渲染的，React的JSX其本质也是React.createElement()的语法糖，和模板本质上也没有太大的差别。而在Angular中，也主要可以通过两种方式来使用模板，一种就是前面所使用的，使用templateUrl来引入一个HTML，来作为模板所要渲染的内容：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-heroes'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./heroes.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./heroes.component.css'</span>]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>另一种就是直接写template来写模板，这倒是和VUE的模板挺像的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'my-app'</span>,</span><br><span class="line">  template: <span class="string">`&lt;h1&gt;Hello &#123;&#123; name &#125;&#125;&lt;/h1&gt;`</span>,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>以上就是Angular的模板的主要使用方式，我个人来看还是第一种比较好，可以有效地把代码的渲染与处理逻辑分离开来，比较有利于代码的可读与可维护。</p>
<h3 id="轻逻辑"><a href="#轻逻辑" class="headerlink" title="轻逻辑"></a>轻逻辑</h3><p>此外，Angular的模板也是比较推崇‘轻逻辑’的设计思路的。也及时说，我们不能在模板里编写非常复杂的JavaScript表达式，对此Angular有以下几点明确的规定：</p>
<ol>
<li>不能在模板new一个对象。</li>
<li>不能使用位运算符。</li>
<li>不能使用++，–运算符。</li>
<li>不能使用=、+=、-=这样的表达式。</li>
</ol>
<p>既然Angular推崇轻逻辑，那么肯定是有原因的，其中一个非常重要的原因是加入我们洗了的模板：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'my-app'</span>,</span><br><span class="line">  template: </span><br><span class="line">  <span class="string">`&lt;ul&gt;</span></span><br><span class="line"><span class="string">    &lt;li *ngFor="let race of races"&gt;</span></span><br><span class="line"><span class="string">        &#123;&#123;race.name&#125;&#125;</span></span><br><span class="line"><span class="string">    &lt;/li&gt;</span></span><br><span class="line"><span class="string">&lt;/ul&gt;`</span>,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>可以肯定的是，浏览器是不会认识*ngFor以及双花括号这些语法的，因此在渲染之前，必须对这些语句进行编译才行。那既然编译，肯定就需要一个编译器了，如果不强调轻逻辑，编译器在保证编译效率的同时，要做的事情就非常多了，编译器的复杂程度也就会提升。而这个JavaScript（or TypeScript）编译器需要在浏览器里面运行，因此当编译器太过复杂时，浏览器很有可能就会无法驾驭这个编译器了。</p>
<p>此外推崇‘轻逻辑’还有一个原因就是：在组件的生命周期中，模板珊瑚会被执行多次，Angular 每次要刷新组件的外观的时候，都需要去调用一下模板函数，如果你在模板里面编写了非常复杂的代码，一定会增加渲染时间，用户一定会感到界面有“卡顿”。</p>
<p>轻逻辑带来了效率上的提升，但也给我们开发者带来了一些不便，比如不能开心在模板里自由自在的撸JavaScript代码了，很多东西也需要额外注意。但总的来讲，这种思路还是很不错的。</p>
<h3 id="Mustache-语法"><a href="#Mustache-语法" class="headerlink" title="Mustache 语法"></a>Mustache 语法</h3><p>Mustache 语法也就是你们说的双花括号语法，这种语法现在已经非常常见了，无论是ES6的模板，还有VUE的模板。在这一点上React和他们还是有点不一样的，React使用的是单花括号，不够大致的思路都是一样的。</p>
<p>插值语法：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'my-app'</span>,</span><br><span class="line">  template: <span class="string">`&lt;h1&gt;Hello &#123;&#123; name &#125;&#125;&lt;/h1&gt;`</span>,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>简单的求值：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'my-app'</span>,</span><br><span class="line">  template: <span class="string">`&lt;h1&gt;1+1=&#123;&#123;1+1&#125;&#125;&lt;/h1&gt;`</span>,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>当然我们也可以定义方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'my-app'</span>,</span><br><span class="line">  template: <span class="string">`可以调用方法&#123;&#123;getVal()&#125;&#125;&lt;/h1&gt;`</span>,</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">public getVal():any&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">65535</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><p>单向的属性绑定：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;img [src]=<span class="string">"imgSrc"</span> /&gt;</span><br><span class="line">public imgSrc:string=<span class="string">"./assets/imgs/1.jpg"</span>;</span><br></pre></td></tr></table></figure></p>
<p>事件绑定：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;button <span class="class"><span class="keyword">class</span></span>=<span class="string">"btn btn-success"</span> (click)=<span class="string">"btnClick($event)"</span>&gt;测试事件&lt;<span class="regexp">/button&gt;</span></span><br></pre></td></tr></table></figure>
<p>事件绑定可以用圆括号来实现，就像上面那样，然后我们就可以在对应的component内部对应方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public btnClick(event):<span class="keyword">void</span>&#123;</span><br><span class="line">    alert(<span class="string">"事件绑定成功！"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>双向绑定我们可以通过方括号里面套一个圆括号来实现，比如上面那个输入hero.name：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;input [(ngModel)]=<span class="string">"hero.name"</span> placeholder=<span class="string">"name"</span>&gt;</span><br></pre></td></tr></table></figure>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/09/11/Angular学习笔记——组件/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/09/11/Angular学习笔记——组件/" itemprop="url">Angular学习笔记——组件</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-11T18:09:18+08:00">
                2018-09-11
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Angular/" itemprop="url" rel="index">
                    <span itemprop="name">Angular</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  822
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  3
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>前端发展到现阶段，组件化也早已深入人心。Angular也不例外，Angular也是围绕着组件化来开发的。我们可以使用Angular CLI，生成一个的新组件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ng generate component heroes</span><br></pre></td></tr></table></figure>
<p>然后我们就可以发现，在可以看到app文件夹下会新增一个叫做heroes的文件夹：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0911/165654_9b56e501_1575229.png" alt="输入图片说明" title="angular_src.png"></p>
<p>然后我们可以打开这个文件夹：app/heroes/heroes.component.ts<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-heroes'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./heroes.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./heroes.component.css'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">HeroesComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line"></span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们可以看到一个组件的组成主要有以下几个部分：</p>
<ul>
<li>@Component就是一个Decorator（装饰器），它指定组件的元数据。</li>
<li>selector：组件的CSS元素选择器。我们就可以这样来使用这个组件：<app-root>。默认情况下，Angular 命令生成出来的组件都会带上一个 app 前缀。</app-root></li>
<li>templateUrl：引用外部的 HTML 模板。如果你想直接编写内联模板，可以使用 template，支持 ES6 引入的“模板字符串”写法。</li>
<li>styleUrls：引用外部 CSS 样式文件，这是一个数组，也就意味着可以引用多份 CSS 文件。</li>
<li>export class AppComponent：这是 ES6 里面引入的模块和 class 定义方式。</li>
</ul>
<p>而ngOnInit则是一个生命周期钩子。Angular会在创建组件后不久调用ngOnInit，这里是放置初始化逻辑的好地方。</p>
<p>然后我们还是按照这个步骤去写一些东西在hero组件上：<br><img src="https://images.gitee.com/uploads/images/2018/0911/170859_21f06a26_1575229.png" alt="输入图片说明" title="hero.png"></p>
<p>然后再将hero组件放在app上：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0911/171058_993c9bf2_1575229.png" alt="输入图片说明" title="apphero.png"></p>
<p>然后我们刷新页面就能看见我们定义的hero显示在页面上了：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0911/171240_85e4fd2b_1575229.png" alt="输入图片说明" title="4200.png"></p>
<p>然后还可以在定义类，来对Hero进行进一步的开发：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// src/app/hero.ts</span></span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">Hero</span> </span>&#123;</span><br><span class="line">    id:number</span><br><span class="line">    name: string</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// src/app/heroes/heroes.component.ts</span></span><br><span class="line"><span class="keyword">import</span> &#123; Component, OnInit &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; Hero &#125; <span class="keyword">from</span> <span class="string">'../hero'</span></span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-heroes'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./heroes.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./heroes.component.css'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">HeroesComponent</span> <span class="title">implements</span> <span class="title">OnInit</span> </span>&#123;</span><br><span class="line">  hero: Hero = &#123;</span><br><span class="line">    id: <span class="number">1</span>,</span><br><span class="line">    name: <span class="string">'Srtian'</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123; &#125;</span><br><span class="line">  ngOnInit() &#123;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在改完上面相关代码后，页面是无法正常渲染的，因为我们原本渲染的hero是一个字符串，而在这我们的hero是一个对象，因此还需要对 templateUrl 里的内容进行修改：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">h2</span>&gt;</span>&#123;&#123;hero.name&#125;&#125;的资料<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span><span class="tag">&lt;<span class="name">span</span>&gt;</span>id:&#123;&#123;hero.id&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span><span class="tag">&lt;<span class="name">span</span>&gt;</span>name:&#123;&#123;hero.name&#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>如此这般，我们就可以在浏览器上访问渲染好的页面了：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0911/172445_4e721f94_1575229.png" alt="输入图片说明" title="srtian1.png"></p>
<p>最后，作为现代前端框架的三巨头，Angular同样也提供了双向绑定。就是这个：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">div&gt;</span><br><span class="line">  &lt;label&gt;name:</span><br><span class="line">    &lt;input [(ngModel)]=<span class="string">"hero.name"</span> placeholder=<span class="string">"name"</span>&gt;</span><br><span class="line">  &lt;<span class="regexp">/label&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>div&gt;</span><br></pre></td></tr></table></figure>
<p>其中[(ngModel)]就像Vue中的v-model一样，提供了双向绑定的功能。但我们也不能直接使用它，还需要在app.module.ts文件中对其进行更改：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; FormsModule &#125; <span class="keyword">from</span> <span class="string">'@angular/forms'</span></span><br><span class="line">imports: [</span><br><span class="line">  BrowserModule,</span><br><span class="line">  FormsModule</span><br><span class="line">],</span><br></pre></td></tr></table></figure>
<p>然后我们就可以刷新页面了：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0911/180242_442d777f_1575229.png" alt="输入图片说明" title="srtain123.png"></p>
<p>此外，每个组件其实都需要进行声明，才能使用，但我们前面好像并没有进行声明呀。原来是因为我们使用Angular CLI来生成该组件时，会在AppModule对HeroesComponent进行自动声明：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// src/app/app.module.ts</span></span><br><span class="line"><span class="keyword">import</span> &#123; HeroesComponent &#125; <span class="keyword">from</span> <span class="string">'./heroes/heroes.component'</span>;</span><br><span class="line">declarations: [</span><br><span class="line">  AppComponent,</span><br><span class="line">  HeroesComponent</span><br><span class="line">],</span><br></pre></td></tr></table></figure>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/09/09/Angular学习笔记——起步/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/09/09/Angular学习笔记——起步/" itemprop="url">Angular学习笔记——起步</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-09T14:55:17+08:00">
                2018-09-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Angular/" itemprop="url" rel="index">
                    <span itemprop="name">Angular</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  618
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  3
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>对于Angular其实早就想学习一番了，毕竟它的所支持的很多东西（比如TypeScript和Rx.js）在我看来都是很有学习的价值的。但由于最近几月事情很多，所以一直没有抽出时间来学习它。前段时间地平线的一位师兄又说到这事，自己下来后好好地想了一想，觉得还是不能将很多事情当做自己不学新东西的借口。所以清理杂念，争取每天都抽出一些时间来学习Angular。此外这些笔记都是基于现在最新的Angular6.17的文档学习的（话说我咋记得我最开始想学Angular的时候版本好像还在5呢，这才几个月就跳了一个版本了。。。。。。）</p>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><p>Angular在安装上和Vue以及React并没有太大的不同，都是通过下载相应的cil，然后就可以搭建好脚手架，直接启动相应的示例项目：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">cnpm install -g @angular/cli</span><br><span class="line">ng new angular-tour-of-heroes</span><br><span class="line">cd angular-tour-of-heroes</span><br><span class="line">ng serve --open</span><br></pre></td></tr></table></figure>
<p>然后我们就可以在浏览器中打开 <a href="http://localhost:4200/" target="_blank" rel="noopener">http://localhost:4200/</a> 就可以。页面的图我就不截了，反正三大框架都差不多。</p>
<p>然后还是老套路，找到主文件：<br><img src="https://images.gitee.com/uploads/images/2018/0909/143435_a979210b_1575229.png" alt="输入图片说明" title="angular_src.png"></p>
<p>然后就可以按照官方文档所说的：<br><img src="https://images.gitee.com/uploads/images/2018/0909/143936_f53e6def_1575229.png" alt="image" title="angular.png"></p>
<p>按照上面的步骤，对其中对应的文件进行修改，首先是app.component.ts下的文件：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// src/app/app.component.ts</span></span><br><span class="line"><span class="keyword">import</span> &#123; Component &#125; <span class="keyword">from</span> <span class="string">'@angular/core'</span>;</span><br><span class="line"></span><br><span class="line">@Component(&#123;</span><br><span class="line">  selector: <span class="string">'app-root'</span>,</span><br><span class="line">  templateUrl: <span class="string">'./app.component.html'</span>,</span><br><span class="line">  styleUrls: [<span class="string">'./app.component.css'</span>]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">AppComponent</span> </span>&#123;</span><br><span class="line">  title = <span class="string">'Tour of Heroes'</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后是相对于的HTML的文件：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--src/app/app.component.html--&gt;</span><br><span class="line">&lt;h1&gt;&#123;&#123;title&#125;&#125;&lt;/h1&gt;</span><br></pre></td></tr></table></figure></p>
<p>就可以得到这样的效果了：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0909/144159_0def8392_1575229.png" alt="输入图片说明" title="4200.png"></p>
<p>（其实Angular和Vue还是有很多相似的地方的，无论是两者统一的使用cil进行脚手架的构建，还是他们的模板语法（双括号）。）</p>
<p>然后我们又可以从src的目录下找到style.css的css文件<br>。它是CLI生成了一个空的css文件。我们可以将应用程序范围的样式放在那里。比如官方示例的CSS代码：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Application-wide Styles */</span></span><br><span class="line"><span class="selector-tag">h1</span> &#123;</span><br><span class="line">  <span class="attribute">color</span>: <span class="number">#369</span>;</span><br><span class="line">  <span class="attribute">font-family</span>: Arial, Helvetica, sans-serif;</span><br><span class="line">  <span class="attribute">font-size</span>: <span class="number">250%</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">h2</span>, <span class="selector-tag">h3</span> &#123;</span><br><span class="line">  <span class="attribute">color</span>: <span class="number">#444</span>;</span><br><span class="line">  <span class="attribute">font-family</span>: Arial, Helvetica, sans-serif;</span><br><span class="line">  <span class="attribute">font-weight</span>: lighter;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">body</span> &#123;</span><br><span class="line">  <span class="attribute">margin</span>: <span class="number">2em</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-tag">body</span>, <span class="selector-tag">input</span><span class="selector-attr">[text]</span>, <span class="selector-tag">button</span> &#123;</span><br><span class="line">  <span class="attribute">color</span>: <span class="number">#888</span>;</span><br><span class="line">  <span class="attribute">font-family</span>: Cambria, Georgia;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* everywhere else */</span></span><br><span class="line">* &#123;</span><br><span class="line">  <span class="attribute">font-family</span>: Arial, Helvetica, sans-serif;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/09/06/深入浅出事件循环机制/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/09/06/深入浅出事件循环机制/" itemprop="url">深入浅出事件循环机制</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-06T12:14:10+08:00">
                2018-09-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,039
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="一、事件循环基础"><a href="#一、事件循环基础" class="headerlink" title="一、事件循环基础"></a>一、事件循环基础</h3><p>由于JavaScript是一种单线程的编程语言，因此JavaScript中的所有任务都需要排队依次完成。但这样的设计明显会有很大的一个问题，那就是如果碰到一个需要耗费很多的时间完成的事件时，很有可能会造成线程的阻塞问题。因此，JavaScript的开发者就将所有的任务分为两种来解决这种问题：</p>
<ul>
<li>同步任务（在主线程中只有前面的代码执行完毕后，后面的才能执行）</li>
<li>异步任务（从主线程提出，进入任务队列执行，等执行完毕后通知主线程，这个异步任务可以执行了，才会进入主线程执行）</li>
</ul>
<p>如图所示：<br><img src="http://www.ruanyifeng.com/blogimg/asset/2014/bg2014100801.jpg" alt="image"></p>
<p>因此总的来说，JavaScript的执行机制主要是以下三步：</p>
<ol>
<li>所有同步任务都在主线程上执行，形成一个执行栈（execution context stack）。</li>
<li>主线程之外，还存在一个”任务队列”（task queue）。只要异步任务有了运行结果，就在”任务队列”之中放置一个事件。</li>
<li>一旦主线程的栈中的所有同步任务执行完毕，系统就会读取任务队列，选择需要首先执行的任务然后执行。</li>
</ol>
<p>而在此过程中，主线程要做的就是从任务队列中去实践，执行事件，执行完毕，再取事件，再执行事件…这样不断取事件，执行事件的循环机制就叫做事件循环机制。（需要注意的的是当任务队列为空时，就会等待直到任务队列变成非空。）</p>
<p>其基本的逻辑如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">while (queue.waitForMessage()) &#123;</span><br><span class="line">  queue.processNextMessage();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>详情也可以看我的这篇文章：</p>
<blockquote>
<p><a href="https://srtian96.gitee.io/blog/2018/05/06/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80/">JavaScript异步编程基础</a></p>
</blockquote>
<h3 id="二、深入事件循环"><a href="#二、深入事件循环" class="headerlink" title="二、深入事件循环"></a>二、深入事件循环</h3><p>上面这种认识也是我最初学习JavaScript所有的认识，但随着自己的学习的不断深入，我开始意识到了这里面的东西没有我所想的这么简单。</p>
<p>首先我们来看一段代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'script start'</span>);</span><br><span class="line"></span><br><span class="line">setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'setTimeout1'</span>);</span><br><span class="line">&#125;, <span class="number">100</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">Promise</span>.resolve().then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'promise1'</span>);</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'promise2'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'setTimeout2'</span>);</span><br><span class="line">&#125;, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'script end'</span>);</span><br></pre></td></tr></table></figure>
<p>输出为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">script start</span><br><span class="line">script end</span><br><span class="line">promise1</span><br><span class="line">promise2</span><br><span class="line">setTimeout2</span><br><span class="line">setTimeout1</span><br></pre></td></tr></table></figure></p>
<p>我们可以看到，Promise都在setTimeout前面执行了，这是为什么呢？</p>
<p>我们要知道的是事件循环并不仅仅只有事件队列，而是具有至少两个队列，除了事件，还要保持浏览器执行的其他操作，而这些操作也被任务，并且分为两类：macrotask（宏任务）和microtask（微任务），在ECMAScript中，microtask称为jobs，macrotask称为task。</p>
<p>那它们到底有什么区别呢？</p>
<ul>
<li>macrotask（宏任务），可以理解是每次执行栈执行的代码就是一个宏任务。主要包括创建主文档对象、解析 HTML、执行主线（或全局）JavaScript<br>代码，更改当前 URL 以及各种事件，如页面加载、输入、网络事件和定时器事件。从浏览器的角度来看，宏任务代表一个个离散的、独立工作单元。运行完任务后，浏览器可以继续其他调度，如重新渲染页面的 UI 或执行垃圾回收。</li>
<li>microtask（微任务）是更小的任务。微任务更新应用程序的状态，但必须在浏览器任务继续执行其他任务之前执行，浏览器任务包括重新渲染页面的UI。微任务的案例包括 promise<br>回调函数、DOM 发生变化等。微任务需要尽可能快地、通过异步方式执行，同时不能产生全新的微任务。微任务使得我们能够在重新渲染UI之前执行指定的行为，避免不必要的UI重绘，UI重绘会使应用程序的状态不连续。</li>
</ul>
<blockquote>
<p>需要的值的是，ECMAScript 规范没有提到事件循环。不过，事件循环在 HTML 规范中有详细说明，里面也讨论了宏任务和微任务的概<br>念。ECMAScript 规范提到了处理 promise 回调（<a href="http://mng.bz/fOlK）的功能（类似于微" target="_blank" rel="noopener">http://mng.bz/fOlK）的功能（类似于微</a><br>任务）。虽然只有 HTML 规范中定义了事件循环，但其他环境（如 Node.js）也都在使用它。</p>
</blockquote>
<p>也就是说事件循环的实现至少应该包含有一个用于红事件的队列和一个用于微事件的队列。这使得事件循环能够根据任务类型进行优先处理。我们还可以看看下面这张图，来看看在存在宏事件与微事件的情况下，事件循环的执行顺序到底是怎么一回事：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0906/115405_54624c91_1575229.png" alt="输入图片说明" title="Event Loop.png"><br>图转自《JavaScript忍者秘籍第二版》</p>
<p>总结起来也就是以下几步：</p>
<ol>
<li>执行一个宏任务（栈中没有就从事件队列中获取）</li>
<li>执行过程中如果遇到微任务，就将它添加到微任务的任务队列中</li>
<li>宏任务执行完毕后，立即执行当前微任务队列中的所有微任务（依次执行）</li>
<li>当前宏任务执行完毕，开始检查渲染，然后GUI线程接管渲染</li>
<li>渲染完毕后，JS线程继续接管，开始下一个宏任务（从事件队列中获取）</li>
</ol>
<p>也正是由于上述的规则，在上面的那段代码中，首先会执行主代码块这个宏事件，然后再将微事件Promise执行，最后再去执行第二个宏事件setTimeout。</p>
<h3 id="三、事件循环与渲染"><a href="#三、事件循环与渲染" class="headerlink" title="三、事件循环与渲染"></a>三、事件循环与渲染</h3><p>前面我们提到，微事件会在宏事件与页面渲染之间执行，那么是事件循环与页面渲染到底存在着怎样的联系呢？</p>
<p>首先我们要知道的是浏览器通常会尝试每秒渲染60次页面，从而达到每秒60帧的数组。而60fps通常是检验体验是否平滑流畅的标准，比方在动画里——这意味着浏览器会尝试在 16ms 内渲染一帧。需要注意上图的的“更新渲染”是如何发生为何<br>事件循环内的，因为在页面渲染时，任何任务都无法再进行修改。这些设计和<br>原则都意味着，如果想要实现平滑流畅的应用，我们是没有太多时间浪费在处<br>理单个事件循环任务的。因此，在理想情况下，单个任务和该任务附属的所有微任务，都应在 16ms 内完成。</p>
<p>因此出于这种考虑，可能会出现以下的三种情况：</p>
<ol>
<li>在另一个 16ms 结束前，事件循环执行到“是否需要进行渲染”的决策环节。因<br>为更新 UI 是一个复杂的操作，所以如果没有显式地指定需要页面渲染，浏览<br>器可能不会选择在当前的循环中执行 UI 渲染操作。</li>
<li>在最后一次渲染完成后大约 16ms，时间循环执行到“是否需要进行渲染”的决<br>策环节。在这种情况下，浏览器会进行 UI 更新，以便用户能够感受到顺畅的<br>应用体验。</li>
<li>执行下一个任务（和相关的所有微任务）耗时超过 16ms。在这种情况下，浏览<br>器将无法以目标帧率重新渲染页面，且 UI 无法被更新。如果任务代码的执行不耗费过多的时间（不超过几百毫秒），这时的延迟甚至可能察觉不到，尤其当页面中没有太多的操作时。反之，如果耗时过多，或者页面上运行有动画时，用户可能会察觉到网络卡顿而不响应。在极端的情况下，如果任务的执行超过几秒，用户的浏览器将会提示“无响应脚本”的恼人信息。</li>
</ol>
<p>参考资料：</p>
<ul>
<li>《JavaScript忍者秘籍第二版》</li>
<li><a href="https://juejin.im/post/5a6547d0f265da3e283a1df7" target="_blank" rel="noopener">https://juejin.im/post/5a6547d0f265da3e283a1df7</a></li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/08/16/浅谈HTTP缓存/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/08/16/浅谈HTTP缓存/" itemprop="url">浅谈HTTP缓存</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-16T12:21:28+08:00">
                2018-08-16
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/性能优化/" itemprop="url" rel="index">
                    <span itemprop="name">性能优化</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,640
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>前天飞猪电面的时候，面试我的那位师兄问了关于性能优化方面的问题，可能是由于有点紧张的缘故，答得不好，很多自己会的东西都没有说出来，而且回想起来我好像只说了个HTTP缓存，且HTTP缓存这块也没完全的说全，哎简直要哭晕在厕所里了。反思的时候想了想，这可能也是自己对这方面的知识虽然知道一些解决方案，但理解还是不够深刻的原因。没能做到提到这方面的问题就能从脑海里浮现出相应的一些解决方案。因此，先写篇关于HTTP缓存文章吧，梳理一下关于HTTP缓存上自己的一些理解。</p>
<h3 id="一、HTTP缓存概述（HTTP-Cache）"><a href="#一、HTTP缓存概述（HTTP-Cache）" class="headerlink" title="一、HTTP缓存概述（HTTP Cache）"></a>一、HTTP缓存概述（HTTP Cache）</h3><p>要搞清楚HTTP缓存，首先当然是要搞清楚缓存是啥，按照MDN的描述，缓存是这样的：</p>
<blockquote>
<p>缓存是一种保存资源副本并在下次请求时直接使用该副本的技术。当 web 缓存发现请求的资源已经被存储，它会拦截请求，返回该资源的拷贝，而不会去源服务器重新下载。这样带来的好处有：缓解服务器端压力，提升性能(获取资源的耗时更短了)。对于网站来说，缓存是达到高性能的重要组成部分。缓存需要合理配置，因为并不是所有资源都是永久不变的：重要的是对一个资源的缓存应截止到其下一次发生改变（即不能缓存过期的资源）。</p>
</blockquote>
<p>上面已经将会缓存是什么描述的很清楚了，而HTTP缓存顾名思义，就是通过HTTP协议，来实现对资源缓存的目的。总的来说，HTTP缓存主要通过两个HTTP头来实现的，其中Expires是由HTTP1.0提供的，而Cache-Control则是由HTTP1.1所提供的：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0802/202340_bbea7d99_1575229.png" alt="HTTP缓存图1.PNG"></p>
<p>下面我们就来对这两个头进行一个了解。</p>
<h3 id="二、Expires"><a href="#二、Expires" class="headerlink" title="二、Expires"></a>二、Expires</h3><p>Expires是由HTTP1.0所提供的支持HTTP缓存的头部，由服务器返回，用GMT格式的字符串表示：</p>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">expires</span>: Tue, 14 Aug 2018 14:32:49 GMT</span><br></pre></td></tr></table></figure>
<p>而读取缓存的条件则是：缓存过期时间（服务器的时间）&lt; 当前时间（客户端的时间）</p>
<p>值得注意的是，我们在expires所设置的时间是一个绝对的时间，而且所参照的是用户电脑上所设置的时间。这种绝对的时间很容易出问题，当用户本地的时间不准确，或用户进行跨时区的移动时，这个时间很可能就会过期，而无法发挥它本应该发挥的作用。</p>
<p>其次，在HTTP1.0里，没有提供相应的配置缓存的方法，只是提供了这个强缓存的头部而已，不足以满足项目对缓存多样化的需求。也正是出于以上两个原因，在HTTP1.1中对HTTP缓存又进行了升级。</p>
<h3 id="三、-Cache-Control"><a href="#三、-Cache-Control" class="headerlink" title="三、 Cache-Control"></a>三、 Cache-Control</h3><p>正是由于Expires存在着很多不足，所以HTTP1.1又为我们提供了 </p>
<p>Cache-Control主要可配置的参数有以下几个：</p>
<ol>
<li>max-age 会指定从请求的时间开始，允许获取的响应被重用的最长时间（单位：秒）。例如，“max-age=60”表示可在接下来的 60 秒缓存和重用响应。</li>
<li>Public 表示响应可被任何缓存区缓存</li>
<li>Private 表示对于单个用户的整个或部分响应消息，不能被共享缓存处理。这些响应通常只为单个用户缓存，因此不允许任何中间缓存对其进行缓存。例如，用户的浏览器可以缓存包含用户私人信息的 HTML 网页，但 CDN 却不能缓存。</li>
<li>no-cache 表示必须先与服务器确认返回的响应是否发生了变化，然后才能使用该响应来满足后续对同一网址的请求。因此，如果存在合适的验证，no-cache 会发起往返通信来验证缓存的响应，但如果资源未发生变化，则可避免下载。</li>
<li>no-store则要简单得多。它直接禁止浏览器以及所有中间缓存存储任何版本的返回响应，例如，包含个人隐私数据或银行业务数据的响应。每次用户请求该资产时，都会向服务器发送请求，并下载完整的响应。</li>
<li>min-fresh 表示客户端可以接收响应时间小于当前时间加上指定时间的响应。（用的不多）</li>
<li>max-stale 表示客户端可以接收超出超时期间的响应消息。如果指定max-stale消息的值，那么客户机可以接收超出超时期指定值之内的响应消息。（用的不多）</li>
</ol>
<h3 id="四、强缓存"><a href="#四、强缓存" class="headerlink" title="四、强缓存"></a>四、强缓存</h3><p>上面已经将Catch-Control做了一个简单的介绍，而具体使用它们二者进行缓存操作的具体实现又分为强缓存与协商缓存。首先来聊一聊强缓存。</p>
<p>强缓存是利用Expires或者Cache-Control这两个http response header实现的，它们都用来表示资源在客户端缓存的有效期。在这个有效期内当浏览器对某个资源的请求命中了强缓存时，其返回的http状态为200，并且不会去对服务器进行请求，而是直接使用其本地的缓存。</p>
<p>具体实现如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">expires: Tue, 21 Aug 2018 10:17:45 GMT</span><br><span class="line">cache-control: max-age=691200</span><br></pre></td></tr></table></figure>
<p>只要存在以上两个头部信息的其中一个，我们就可以对资源进行强缓存了。另外需要注意的是，当Catch-Control的优先级是要高于expires的。</p>
<p>总的来说，强缓存是前端性能优化的一大助力。当我们页面存在很多长期不变的静态资源时，都应该对其进行强缓存的处理，我们通常可以为这些静态资源全部配置一个超时时间很长的Expires或Cache-Control。当用户在访问网页时，就只会在第一次加载时从服务器请求静态资源，在往后访问该页面时，就只要缓存没有失效并且用户没有强制刷新的条件下都会从自己的缓存中加载。这样既节省了资源加载的时间的消耗，又不会去访问服务器，可以有效地为服务器减压。</p>
<p>不过强缓存也存在一个很大的弊端，那就是对于动态资源它就有点力不从心了。因为如果我们对动态资源进行了强缓存，那么很可能会在这动态资源更改后，浏览器还是会直接去请求没有更改前的动态资源。也这是由于这方面的考虑，在强缓存外还存在着协商缓存的缓存方案。</p>
<h3 id="五、协商缓存"><a href="#五、协商缓存" class="headerlink" title="五、协商缓存"></a>五、协商缓存</h3><p>当浏览器对某个资源的请求没有命中强缓存，就会发一个请求到服务器，验证协商缓存是否命中，如果协商缓存命中，请求响应返回的http状态为304并且会显示一个Not Modified的字符串；<br>若未命中请求，则将资源返回客户端，并更新本地缓存数据，并返回200的状态码。</p>
<p>除此之外，我们也可以设置为协商缓存，以解决动态资源缓存与更新的问题，首先我们来看一张关于协商缓存的图：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0816/113410_ac217adc_1575229.png" alt="输入图片说明"></p>
<p>可以看到，在这个实现了协商缓存的Cache-Control中，设置了no-catch，当我们设置为no-catch时，我们就是可以直接去访问服务器，去查看该资源的更改情况，已确定是是否需要使用缓存。而在校验的这一步我们就需要使用以下几个头来帮助验证资源的更改情况了：</p>
<ul>
<li>Last-Modified：表示这个响应资源的最后修改时间。web服务器在响应请求时，会告诉浏览器该资源的最后修改时间，但它的最小单位是秒级，也就是如果我们在1秒内多次修改该资源，那么Last-Modified也无法发挥其应有的作用。</li>
<li>If-Modified-Since：当资源过期时（强缓存失效），发现资源具有Last-Modified声明，则再次向web服务器请求时带上头 If-Modified-Since，表示请求时间。web服务器收到请求后发现有头If-Modified-Since 则与被请求资源的最后修改时间进行比对。若最后修改时间较新，说明资源又被改动过，则响应整片资源内容（写在响应消息包体内），HTTP 200；若最后修改时间较旧，说明资源无新修改，则响应HTTP 304 (无需包体，节省浏览)，告知浏览器继续使用所保存的cache。</li>
</ul>
<p>也正是由于 Last-Modified存在着缺陷，我们就需要ETag来帮助我们来对资源的更改进行判断：</p>
<ul>
<li>Etag：当Web服务器响应请求时，会告诉浏览器当前资源在服务器的唯一标识（生成规则是由服务器决定的）。就比如在Apache中，ETag的值，其默认是对文件的索引节（INode），大小（Size）和最后修改时间（MTime）进行Hash后得到的。</li>
<li>If-None-Match：当资源过期时，如果发现资源具有Etage声明，则再次向web服务器请求时带上头If-None-Match （Etag的值）。Web服务器收到请求后发现有头If-None-Match， 就会将其被请求的资源的相应校验字段进行对比，然后再决定返回200或304。</li>
</ul>
<p>这就是强缓存与协商缓存的大部分情况了，具体的流程可见下图：</p>
<p><img src="http://juanha.coding.me/2017/03/05/http-cache/http-cache.png" alt="image"></p>
<p>原图链接：<a href="http://juanha.coding.me/2017/03/05/http-cache/http-cache.png" target="_blank" rel="noopener">http://juanha.coding.me/2017/03/05/http-cache/http-cache.png</a></p>
<h4 id="六、定义最佳-Cache-Control-策略"><a href="#六、定义最佳-Cache-Control-策略" class="headerlink" title="六、定义最佳 Cache-Control 策略"></a>六、定义最佳 Cache-Control 策略</h4><p><img src="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/images/http-cache-decision-tree.png" alt="image"></p>
<p>通常我们可以按照上面这张流程图来对HTTP缓存进行相应的配置，详情可以看这篇文章：</p>
<blockquote>
<p><a href="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching" target="_blank" rel="noopener">https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching</a>?</p>
</blockquote>
<p>这位大佬对缓存的配置做了一个很好的阐述。</p>
<p>参考资料：</p>
<ul>
<li><a href="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching" target="_blank" rel="noopener">https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching</a>?</li>
<li><a href="https://www.cnblogs.com/lyzg/p/5125934.html#_label3" target="_blank" rel="noopener">https://www.cnblogs.com/lyzg/p/5125934.html#_label3</a></li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching_FAQ" target="_blank" rel="noopener">https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching_FAQ</a></li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/08/08/ECMAScipt5.1文档阅读笔记——Object类型/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/08/08/ECMAScipt5.1文档阅读笔记——Object类型/" itemprop="url">ECMAScript5.1文档阅读笔记——Object类型</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-08T17:12:22+08:00">
                2018-08-08
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  904
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  3
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>起床有点发烧，因此学些新东西有点力不从心了，所以想了想还是复习复习JavaScript吧。然后想着ES6虽然用的还蛮多的，但ES5才是本源啊，就找到了ECMAScipt5.1文档读了部分自己感兴趣的部分，还可以学学英语，做个笔记。。。</p>
<blockquote>
<p><a href="http://www.ecma-international.org/ecma-262/5.1/" target="_blank" rel="noopener">http://www.ecma-international.org/ecma-262/5.1/</a></p>
</blockquote>
<h3 id="Object-类型"><a href="#Object-类型" class="headerlink" title="Object 类型"></a>Object 类型</h3><p>这部分大体上我在看高程的时候就已经知道了，不过这三种属性竟然都属于Object类型，而不是包含关系，这倒是让我涨姿势了。</p>
<p>。首先Object是一个属性的集合。这里说的属性可以是数据属性，也可以是访问器属性，也可以是内部属性。</p>
<ul>
<li>数据属性（data property）</li>
<li>访问器属性：Vue的双向绑定就靠它</li>
<li>内部属性（internal property）：对于这个属性，我们不能直接通过JavaScript来操作，就比如[[prototype]],我们就不能直接操作，因此在对象中我们通过<strong>proto</strong>来访问它。</li>
</ul>
<h3 id="Property-Attributes"><a href="#Property-Attributes" class="headerlink" title="Property Attributes"></a>Property Attributes</h3><p>这部分主要是讲了数据属性和访问器属性，大致上好像和高程说的没什么两样，两者都是四个特性：</p>
<h5 id="数据属性："><a href="#数据属性：" class="headerlink" title="数据属性："></a>数据属性：</h5><ul>
<li>[[Value]]：值</li>
<li>[[Writable]]：布尔类型，表示可写。如果设置为false，就无法更改value的值。</li>
<li>[[Enumerable]]：布尔类型，表示可枚举。如果设置为false,就无法被for-in等枚举出来。</li>
<li>[[Configurable]]：布尔类型，如果设置为false。就无法删除该属性或者改变该属性为访问器属性，也无法改变它的特性。</li>
</ul>
<h5 id="访问器属性："><a href="#访问器属性：" class="headerlink" title="访问器属性："></a>访问器属性：</h5><ul>
<li>[[Get]]：是一个Object or Undefined。如果是一个 Object 对象，那么它必须就是一个函数对象。用于获取值</li>
<li>[[Set]]：同上，不同的是它用于设置值，Vue的数据劫持就靠这两个属性来实现的。</li>
<li>[[Enumerable]]：同数据属性</li>
<li>[[Configurable]]：同数据属性</li>
</ul>
<h4 id="内部属性："><a href="#内部属性：" class="headerlink" title="内部属性："></a>内部属性：</h4><p>对于内部属性我认识的并不多，其一是由于所看的书好像都没有对内部属性有个完整的介绍，其二是由于内部属性都无法直接访问，因此用的少。不过按照文档的描述，这些内部属性倒不是 ECMAScript的一部分，知识为了说明他们而定义的，也就是说有这么一个内部实现在这里，但其实本质上他们并不是ECMAScript的一份子，只是为了描述这些内部实现而搞的东西而已。下面这是文档中的表8，适用于所有 ECMAScript 对象的内部属性：（还有一个表9，表示部分对象存在的内部属性，其文档对于这个表也没啥解说，因此我就不知道了。。。）<br><img src="https://images.gitee.com/uploads/images/2018/0808/163603_47686baa_1575229.png" alt="image"><br>挑重要的说：</p>
<ul>
<li>[[Prototype]]：这玩意所有对象都有，可以说是最重要的一个内部属性了（我个人是这么认为的），因为在JavaScript中，对象都靠它来实现继承，也就是我们通常所说的原型。按照规范上的描述，所有的原型链必须是有限长度的，终点便是null。</li>
<li>[[Class]]：这个 内部属性的值用于内部区分对象的种类。这东西就是Object.prototype.toString.call的原理所在，规范中只有Object.prototype.toString.call可以访问这个属性</li>
<li>[[Get]]：返回命名属性的值</li>
<li>[[Put]]：将指定的属性设置为第二个参数的值。</li>
</ul>
<p>其他的对我来讲，用的都不多，就不扯了。后面规范都扯[[GetOwnProperty]]，本来就不舒服，还绕来绕去的，看的头晕。。。</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/08/04/Rx.js学习体会（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/08/04/Rx.js学习体会（一）/" itemprop="url">Rx.js学习所得</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-04T19:05:07+08:00">
                2018-08-04
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Rx-js/" itemprop="url" rel="index">
                    <span itemprop="name">Rx.js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,813
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>学习Rx.js也差不多3个来月了（准确来讲，应该是第一次学习失败，隔了一个月第二次总算是有点理解它的思想了）。不得不说，这玩意虽然挺有意思的，但真滴难。其体系是有点庞杂的，操作符是真滴多（还要吐槽文档也不行。。。），但总的来说，虽然还没用上Rx.js,但就目前学习它的所得，倒是让我收获颇丰。所以写篇文章总结一下自己的体会还是很有必要的，后面也需要写不少文章来记录操作符的一些学习所得，以备忘记（记性不好的是真滴难受）。</p>
<h3 id="一、学习动机"><a href="#一、学习动机" class="headerlink" title="一、学习动机"></a>一、学习动机</h3><p>总的来说，第一次学习Rx.js是由于看了篇文章，感觉这种东西是有点厉害，加上当时学习redux，同样都体现着函数式编程的思想。因此希望可以从Rx.js中对函数式编程上有所收获，所以就学了一下。结果一看文档，那面屏幕的操作符看的我一脸懵逼，而且也苦苦不能理解它的抽象思想，结果学了1个星期就放弃了。第二次学习则是在看了下redux-saga的文档后，自我感觉不咋喜欢它的语法，感觉还是async/await要优雅些，觉得做个写代码的要求有点追求，经过了解后知道了有个东西叫redux-observable，看了一下代码示例，纯粹的对象字面量的actions，有点厉害的，就打算学一学看看。仔细一看是基于rx.js的，所以弄到头还是得硬上Rx.js。不过这次倒是坚持下来了，虽然还没上手实践它，但总算是理解了它的思想，并通过学习它对很多以往虽然有学习过，但体会不深的东西也有了更为深刻的理解。</p>
<p>总的来说，有以下收获：</p>
<ul>
<li>理解函数式编程的思想</li>
<li>理解响应式编程的思想</li>
<li>抽象的能力提升</li>
<li>Rx.js</li>
</ul>
<h3 id="二、函数式编程的思想"><a href="#二、函数式编程的思想" class="headerlink" title="二、函数式编程的思想"></a>二、函数式编程的思想</h3><p>现在回想起来，第一次之所以没有很好地理解Rx.js，其中很大的原因是对函数式编程的思想理解的不够（当然现在还是不够），虽然当时学习了Redux，也在用它实践，但对其的理解还是不够透彻。而第二次学习则算是理解了Redux的一些思想（纯函数，数据的不可变）。因此在第二次学习Rx.js的时候，要轻松不少，而且对函数式编程的思想也有了更为深刻的理解。</p>
<p>所谓纯函数，其实就是要满足以下两个条件：</p>
<ol>
<li>函数的执行结果是由输入参数所决定的，不受除参数之外的任何数据的影响</li>
<li>函数中不会修改任何外部的状态。</li>
</ol>
<p>对于这两方面可以看一个示例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line"><span class="keyword">const</span> addVal = <span class="function">(<span class="params">arr, newVal</span>) =&gt;</span> &#123;</span><br><span class="line">    arr.push(newVal)</span><br><span class="line">    <span class="keyword">return</span> arr</span><br><span class="line">&#125;</span><br><span class="line">addVal(arr, <span class="number">6</span>)</span><br><span class="line"><span class="built_in">console</span>.log(arr) <span class="comment">// [1, 2, 3, 4, 6]</span></span><br></pre></td></tr></table></figure>
<p>就比如上面的代码，add函数在内部直接调用push函数，将新元素直接添加到数组的尾部，这样就会直接改变数组的值。这样看起来好像并没有什么副作用，但仔细想想，假如这是一份数据，当我们将数据传入这个函数的时候，将原数据进行直接修改，这很容易导致其他引用此数据的函数出现意料不到的问题。就比如下面这个：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]</span><br><span class="line"><span class="keyword">const</span> addOne = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.map(<span class="function"><span class="params">newVal</span> =&gt;</span> newVal + <span class="number">1</span>)</span><br><span class="line"><span class="keyword">const</span> addVal = <span class="function">(<span class="params">arr, newVal</span>) =&gt;</span> &#123;</span><br><span class="line">    arr.push(newVal)</span><br><span class="line">    <span class="keyword">return</span> arr</span><br><span class="line">&#125;</span><br><span class="line">addVal(arr, <span class="number">6</span>)</span><br><span class="line">addOne(arr)</span><br></pre></td></tr></table></figure>
<p>可以看到上述代码，我们在addOne(arr)所期望的结果是原本的arr数组内的所有元素都加上1，但实际结果却是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[2, 3, 4, 5, 7]</span><br></pre></td></tr></table></figure>
<p>所产生的结果与我们所预料的完全不同。也正是出于这番原因，我们在使用redux的时候，在reducer中，也作出要求：数据是不可变的，就是为了避免诸如此类的事情的发生。出于这番考虑，我们就可以通过对上述代码进行修改，以满足我们的需求：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]</span><br><span class="line"><span class="keyword">const</span> addOne = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.map(<span class="function"><span class="params">newVal</span> =&gt;</span> newVal + <span class="number">1</span>)</span><br><span class="line"><span class="keyword">const</span> addVal = <span class="function">(<span class="params">arr, newVal</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> [...arr, newVal]</span><br><span class="line">&#125;</span><br><span class="line">addVal(arr, <span class="number">6</span>)</span><br><span class="line">addOne(arr)</span><br></pre></td></tr></table></figure>
<p>现在再去执行，就可以发现，我们所得的结果与我们所期望的是一致的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[2, 3, 4, 5]</span><br></pre></td></tr></table></figure>
<p>因此总计一下我现阶段所理解的函数式编程：将一个个操作数据的方法用函数进行封装，并且要满足以下的条件：</p>
<ul>
<li>这个函数是一个纯函数。</li>
<li>数据是不可变的，因此返回时返回一个新的数据，而不是在原有数据上进行修改。</li>
</ul>
<p>也正是出于以上的这些考虑，在Rx.js中，我们每个Observable对象都会返回一个Observable对象：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]</span><br><span class="line"><span class="keyword">const</span> result$ = arr$.filter(<span class="function"><span class="params">x</span> =&gt;</span> x % <span class="number">2</span> === <span class="number">0</span>).map(<span class="function"><span class="params">x</span> =&gt;</span> x * <span class="number">2</span>)</span><br><span class="line">result$.subscribe(<span class="built_in">console</span>.log)</span><br><span class="line"><span class="comment">// 4 8</span></span><br></pre></td></tr></table></figure>
<p>之所以Rx.js可以完成上述的这种操作其实就是由于filter和map都是Observable对象且它会返回一个新的Observable对象，不会对原有的Observable对象进行修改。</p>
<h3 id="三、响应式编程的思想"><a href="#三、响应式编程的思想" class="headerlink" title="三、响应式编程的思想"></a>三、响应式编程的思想</h3><p>对于响应式编程，我感觉最近几年用的很广。别的不说，Vue就是其中的代表，另外还有mobx也是其中一员。以我现在的理解就是这样：本质上有点观察者模式的意思。将数据的产生与数据的处理逻辑相分离，在观察者observer方面无需关系数据的来源，只管负责处理数据的逻辑的实现，而被观察者Observable则只要关系产生数据流，并通知所有注册的观察者，无需担心这些数据是如何被处理的。</p>
<p>有个例子提的很好，就像EXCEL的表格，每个格子的输入我们都可以将其看做一个数据流，用户在哪个格子输入是我们事先无法预料的，但我们也无需关心这些，我们只要将这些输入一视同仁的看做数据流，只要数值发生改变，我们就进行相应的处理。</p>
<p>在我的理解中，其实光有响应式编程其实还是有所不足的，如果我们只是单纯的这些事件抽象为数据流，并对这个数据流进行处理，不做规范的话，可能会出现数据状态不好管理的情况，就比如我上面举的那个函数式编程的例子。我们对数据流进行操作后，如果直接改动数据流，很可能会导致一些我们无法预料的事情发生。因此，函数编程+响应式编程才能将两者的优点都吸收，这也就是Rx.js的魅力所在吧。</p>
<h3 id="待续"><a href="#待续" class="headerlink" title="待续"></a>待续</h3>
          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/08/01/Node.js异步IO模型/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/08/01/Node.js异步IO模型/" itemprop="url">Node.js异步IO模型</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-01T13:08:27+08:00">
                2018-08-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Node-js/" itemprop="url" rel="index">
                    <span itemprop="name">Node.js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,889
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>最近在学习 HTTP 和 Node.js 相关的一些东西，越发感觉对以往没搞明白的一些问题自然而然的懂了（比如浏览器缓存方面）。因此决定先把前后端的开发的相关领域给打通，对每个环节都有一个较为全面的了解。这应该会对自己对于整个项目开发流程的理解会有一个较大的提升。</p>
<p>注：此篇文章主要是：<br><a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/" target="_blank" rel="noopener">https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/</a><br>的体会加上了自己的一些体会。但由于这篇文章是纯英文的，后面的部分还是没有很好地理解。往后需要根据自己对这些东西的理解与后面重复看这篇文章的体会来进行补充。</p>
<h3 id="一、事件循环"><a href="#一、事件循环" class="headerlink" title="一、事件循环"></a>一、事件循环</h3><p>我以前也总结过关于JavaScript的事件循环机制：</p>
<blockquote>
<p><a href="http://srtian96.gitee.io/blog/2018/05/06/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80/">http://srtian96.gitee.io/blog/2018/05/06/JavaScript%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80/</a></p>
</blockquote>
<p>同样的在Node.js中Event Loop也是其执行机制的重要的一环，Event Loop的职责就在于不断的等待事件的发生，然后将这个事件的所有处理器一他们订阅这个事件的时间顺序依次执行，当这个事件的所有处理器都被执行完毕后，事件循环就会开始继续等待下一个事件的出发，不断往复，直到所有事件全部执行完毕。</p>
<p>虽然这样说起来 Event Loop并不复杂，但在Node.js中，Event Loop存在着属于自己的规则。我们首先来看下面的这段代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123; readFile &#125; = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"><span class="keyword">const</span> EventEmitter = <span class="built_in">require</span>(<span class="string">'events'</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Events</span> <span class="keyword">extends</span> <span class="title">EventEmitter</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> call = <span class="keyword">new</span> Events()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">call.on(<span class="string">'call'</span>, () =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'call 执行拉！'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'0 毫秒后执行此回调'</span>)</span><br><span class="line">&#125;, <span class="number">0</span>)</span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'200 毫秒后执行此回调'</span>)</span><br><span class="line">&#125;, <span class="number">200</span>)</span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'100 毫秒后执行此回调'</span>)</span><br><span class="line">&#125;, <span class="number">100</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'这里是global'</span>)</span><br><span class="line">readFile(<span class="string">'DOM.html'</span>, <span class="string">'utf-8'</span>, data =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'读取了DOM文件'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">setImmediate(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'immediate执行了'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">readFile(<span class="string">'package.json'</span>, <span class="string">'utf-8'</span>, data =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'读取了package文件'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">process.nextTick(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'process.nextTick 执行了'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">Promise</span>.resolve()</span><br><span class="line">    .then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        call.emit(<span class="string">'call'</span>)</span><br><span class="line"></span><br><span class="line">        process.nextTick(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'这是Promise里的process.nextTick'</span>)</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'第一个Promise then'</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'第二个Promise then'</span>)</span><br><span class="line">    &#125;)</span><br></pre></td></tr></table></figure>
<p>如果对Node.js事件循环机制熟悉的大佬，应该仔细看看就知道它的打印结果了，而像我这样的咸鱼在没有好好了解Node.js事件循环机制的人来说，将打印结果事先确定就有点难度了，但没关系，都是需要学习的嘛！要搞清楚这个问题，首先我们要清楚的是，虽然Node.js采用V8引擎作为JavaScript的执行引擎，但同时也使用了libuv来实现自己的事件驱动式的异步I/O。因此要搞清楚Node.js的时间循环机制，最好的方式就是去看libuv的源码了。不过libuv的源码是C++的，所以在网上有搜了下，挺快的就搜到了关于这段代码的注释：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//deps/uv/src/unix/core.c</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">uv_run</span><span class="params">(<span class="keyword">uv_loop_t</span> *loop, uv_run_mode mode)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> timeout;</span><br><span class="line">	<span class="keyword">int</span> r;</span><br><span class="line">	<span class="keyword">int</span> ran_pending;</span><br><span class="line">	<span class="comment">//uv__loop_alive返回的是event loop中是否还有待处理的handle或者request</span></span><br><span class="line">	<span class="comment">//以及closing_handles是否为NULL,如果均没有,则返回0</span></span><br><span class="line">	r = uv__loop_alive(loop);</span><br><span class="line">	<span class="comment">//更新当前event loop的时间戳,单位是ms</span></span><br><span class="line">	<span class="keyword">if</span> (!r)</span><br><span class="line">    	uv__update_time(loop);</span><br><span class="line">	<span class="keyword">while</span> (r != <span class="number">0</span> &amp;&amp; loop-&gt;stop_flag == <span class="number">0</span>) &#123;</span><br><span class="line">    	<span class="comment">//使用Linux下的高精度Timer hrtime更新loop-&gt;time,即event loop的时间戳</span></span><br><span class="line">    	uv__update_time(loop);</span><br><span class="line">    	<span class="comment">//执行判断当前loop-&gt;time下有无到期的Timer,显然在同一个loop里面timer拥有最高的优先级</span></span><br><span class="line">    	uv__run_timers(loop);</span><br><span class="line">    	<span class="comment">//判断当前的pending_queue是否有事件待处理,并且一次将&amp;loop-&gt;pending_queue中的uv__io_t对应的cb全部拿出来执行</span></span><br><span class="line">    	ran_pending = uv__run_pending(loop);</span><br><span class="line">    	<span class="comment">//实现在loop-watcher.c文件中,一次将&amp;loop-&gt;idle_handles中的idle_cd全部执行完毕(如果存在的话)</span></span><br><span class="line">    	uv__run_idle(loop);</span><br><span class="line">    	<span class="comment">//实现在loop-watcher.c文件中,一次将&amp;loop-&gt;prepare_handles中的prepare_cb全部执行完毕(如果存在的话)</span></span><br><span class="line">    	uv__run_prepare(loop);</span><br><span class="line"></span><br><span class="line">    	timeout = <span class="number">0</span>;</span><br><span class="line">    	<span class="comment">//如果是UV_RUN_ONCE的模式,并且pending_queue队列为空,或者采用UV_RUN_DEFAULT(在一个loop中处理所有事件),则将timeout参数置为</span></span><br><span class="line">    	<span class="comment">//最近的一个定时器的超时时间,防止在uv_io_poll中阻塞住无法进入超时的timer中</span></span><br><span class="line">    	<span class="keyword">if</span> ((mode == UV_RUN_ONCE &amp;&amp; !ran_pending) || mode == UV_RUN_DEFAULT)</span><br><span class="line">        	timeout = uv_backend_timeout(loop);</span><br><span class="line">    	<span class="comment">//进入I/O处理的函数(重点分析的部分),此处挂载timeout是为了防止在uv_io_poll中陷入阻塞无法执行timers;并且对于mode为</span></span><br><span class="line">    	<span class="comment">//UV_RUN_NOWAIT类型的uv_run执行,timeout为0可以保证其立即跳出uv__io_poll,达到了非阻塞调用的效果</span></span><br><span class="line">    	uv__io_poll(loop, timeout);</span><br><span class="line">    	<span class="comment">//实现在loop-watcher.c文件中,一次将&amp;loop-&gt;check_handles中的check_cb全部执行完毕(如果存在的话)</span></span><br><span class="line">    	uv__run_check(loop);</span><br><span class="line">    	<span class="comment">//执行结束时的资源释放,loop-&gt;closing_handles指针指向NULL</span></span><br><span class="line">    	uv__run_closing_handles(loop);</span><br><span class="line"></span><br><span class="line">    	<span class="keyword">if</span> (mode == UV_RUN_ONCE) &#123;</span><br><span class="line">        	<span class="comment">//如果是UV_RUN_ONCE模式,继续更新当前event loop的时间戳</span></span><br><span class="line">        	uv__update_time(loop);</span><br><span class="line">        	<span class="comment">//执行timers,判断是否有已经到期的timer</span></span><br><span class="line">        	uv__run_timers(loop);</span><br><span class="line">    	&#125;</span><br><span class="line">    	r = uv__loop_alive(loop);</span><br><span class="line">    	<span class="comment">//在UV_RUN_ONCE和UV_RUN_NOWAIT模式中,跳出当前的循环</span></span><br><span class="line">    	<span class="keyword">if</span> (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)</span><br><span class="line">        	<span class="keyword">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">	<span class="comment">//标记当前的stop_flag为0,表示当前的loop执行完毕</span></span><br><span class="line">	<span class="keyword">if</span> (loop-&gt;stop_flag != <span class="number">0</span>)</span><br><span class="line">    	loop-&gt;stop_flag = <span class="number">0</span>;</span><br><span class="line">	<span class="comment">//返回r的值</span></span><br><span class="line">	<span class="keyword">return</span> r;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后我们就可以再根据这张广为流传的Node.js的流程图一起学习：</p>
<p><img src="https://upload-images.jianshu.io/upload_images/2463185-5e13c3082d4c395f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/470" alt="image"></p>
<p>官方的还有个这种流程图：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">   ┌───────────────────────────┐</span><br><span class="line">┌─&gt;│           timers          │</span><br><span class="line">│  └─────────────┬─────────────┘</span><br><span class="line">│  ┌─────────────┴─────────────┐</span><br><span class="line">│  │     pending callbacks     │</span><br><span class="line">│  └─────────────┬─────────────┘</span><br><span class="line">│  ┌─────────────┴─────────────┐</span><br><span class="line">│  │       idle, prepare       │</span><br><span class="line">│  └─────────────┬─────────────┘      ┌───────────────┐</span><br><span class="line">│  ┌─────────────┴─────────────┐      │   incoming:   │</span><br><span class="line">│  │           poll            │&lt;─────┤  connections, │</span><br><span class="line">│  └─────────────┬─────────────┘      │   data, etc.  │</span><br><span class="line">│  ┌─────────────┴─────────────┐      └───────────────┘</span><br><span class="line">│  │           check           │</span><br><span class="line">│  └─────────────┬─────────────┘</span><br><span class="line">│  ┌─────────────┴─────────────┐</span><br><span class="line">└──┤      close callbacks      │</span><br><span class="line">   └───────────────────────────┘</span><br></pre></td></tr></table></figure>
<p>总结起来主要有以下几个阶段：</p>
<ul>
<li>定时器：这一阶段会执行由 setTimeout() 和 setInterval() 所设置的回调。</li>
<li>I/O 回调：执行除了关闭回调、定时器的回调和 setImmediat() 以外的几乎所有的回调。</li>
<li>ide，prepare：仅内部使用。</li>
<li>轮询：检索新的I / O事件;执行与I/O相关的回调（几乎所有回调都是关闭回调，定时器和setImmediate（）调度的回调）;node 将在适当的时候阻塞在这里。</li>
<li>check： setImmediate() 的回调。</li>
<li>关闭事件回调：比如 socket.on(‘close’, …) 的回调。</li>
</ul>
<p>注：每一格称为事件循环的一个阶段。</p>
<p>值的注意的是，以上的每一阶段都有一个先进先出的待执行任务队列。而且在每一阶段，其内部都有自己的执行方法，当进入其中一个阶段时，每个阶段都会执行任何该阶段自己特定的操作，然后才执行在该阶段的队列中的回调，直到队列里的回调都执行完了或执行的次数达到最大限制。当队列耗尽或执行的次数达到最大限制时，事件循环进入下一个阶段，如此循环。</p>
<p>因此按照上面的思路，我们逐个分析可以得到，上面的那串代码的执行结果如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">这里是global</span><br><span class="line">process.nextTick 执行了</span><br><span class="line">call 执行拉！</span><br><span class="line">第一个Promise then</span><br><span class="line">第二个Promise then</span><br><span class="line">这是Promise里的process.nextTick</span><br><span class="line">0 毫秒后执行此回调</span><br><span class="line">immediate执行了</span><br><span class="line">读取了package文件</span><br><span class="line">读取了DOM文件</span><br><span class="line">100 毫秒后执行此回调</span><br><span class="line">200 毫秒后执行此回调</span><br></pre></td></tr></table></figure></p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/blog/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/blog/">1</a><span class="page-number current">2</span><a class="page-number" href="/blog/page/3/">3</a><span class="space">&hellip;</span><a class="page-number" href="/blog/page/6/">6</a><a class="extend next" rel="next" href="/blog/page/3/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  

  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
